package com.spike.servlet;

import com.spike.model.User;
import com.spike.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService userService = new UserService();
        try {
            User byUP = userService.findByUP(username, password);
            if (byUP != null) {
                req.setAttribute("login", byUP);
                req.getRequestDispatcher("WEB-INF/jsp/index.jsp").forward(req, resp);
            }else {
                req.setAttribute("username",username);
                req.setAttribute("password",password);
                req.setAttribute("msg", "用户名或密码错误");
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
